package logic

import (
	"context"
	"encoding/json"
	redis2 "gitee.com/Cauchy_AQ/vxopen/model/redis"
	"gitee.com/Cauchy_AQ/vxopen/utils"

	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/internal/svc"
	"gitee.com/Cauchy_AQ/vxopen/rpc/transform/transform"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserClickLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserClickLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserClickLogic {
	return &UserClickLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserClickLogic) UserClick(in *transform.UserClickReq) (*transform.UserClickResp, error) {
	userInfo := new(transform.UserInfoResp)
	if err := json.Unmarshal(in.Message, userInfo); err != nil {
		return nil, err
	}

	// 1. 点击量（pv）
	pvKey := redis2.CacheDayClickPrefix + utils.GetTodayFormat()
	_, _ = l.svcCtx.RDB.Incr(context.Background(), redis2.CacheClickPrefix).Result()
	_, _ = l.svcCtx.RDB.Incr(context.Background(), pvKey).Result()
	_, _ = l.svcCtx.RDB.Expire(context.Background(), pvKey, redis2.CacheDayClickPrefixTimeout).Result()

	// 2. 总访问次数（uv）
	hllVal := utils.GetTodayFormat() + userInfo.Name
	_, _ = l.svcCtx.RDB.PFAdd(context.Background(), redis2.CacheVisitPrefix, hllVal).Result()
	uvKey := redis2.CacheDayVisitPrefix + utils.GetTodayFormat()
	_, _ = l.svcCtx.RDB.PFAdd(context.Background(), uvKey, hllVal).Result()
	_, _ = l.svcCtx.RDB.Expire(context.Background(), uvKey, redis2.CacheDayVisitPrefixTimeout).Result()

	return &transform.UserClickResp{}, nil
}
